package com.uniview.util.mail;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.springframework.stereotype.Service;

import com.uniview.entity.po.ServiceOrders;
import com.uniview.entity.vo.MailMsg;

/**
 * 简单邮件（不带附件的邮件）发送器
 * 
 * @author Qingtian Lei
 * @date 创建时间：2018年09月03日
 * @version
 */
@Service("simpleMailSenderDB")
public class SimpleMailSenderDB {

	private final transient Properties props = System.getProperties();

	private transient MailAuthenticator authenticator;

	private transient Session session;

	private String MAIL_SMTP_HOST;

	private String MAIL_SMTP_PORT;

	private String MAIL_SMTP_AUTH;

	private String USERNAME;

	private String PASSWORD;

	public SimpleMailSenderDB() {
	}

	public SimpleMailSenderDB(String mail_smtp_host, String mail_smtp_post,
			String mail_smtp_auth, String username, String password) {
		this.MAIL_SMTP_HOST = mail_smtp_host;
		this.MAIL_SMTP_PORT = mail_smtp_post;
		this.MAIL_SMTP_AUTH = mail_smtp_auth;
		this.USERNAME = username;
		this.PASSWORD = password;
	}

	/**
	 * 初始化
	 * 
	 * 创建时间：2017年2月28日
	 * 
	 * @author HY
	 * @param smtpHostName
	 *            SMTP服务器地址
	 * @param username
	 *            发送邮件的用户名（邮箱地址）
	 * @param password
	 *            密码
	 */
	public void init() {
		// 初始化Properties
		props.put("mail.smtp.host", MAIL_SMTP_HOST);
		props.put("mail.smtp.port", MAIL_SMTP_PORT);
		props.put("mail.smtp.auth", MAIL_SMTP_AUTH);
		// 验证发送者账户密码
		authenticator = new MailAuthenticator(USERNAME, PASSWORD);
		// 创建Session
		session = Session.getInstance(props, authenticator);
	}

	/**
	 * 发送邮件（单发）
	 * 
	 * 创建时间：2018年09月03日
	 * 
	 * @author Qingtian Lei
	 * @param recipient
	 *            收件人邮箱地址
	 * @param subject
	 *            邮件主题
	 * @param content
	 *            邮箱内容
	 * @throws AddressException
	 * @throws MessagingException
	 */
	public void send(String recipient, String subject, Object content)
			throws AddressException, MessagingException {
		// 1.创建mime类型邮件
		final Message message = new MimeMessage(session);
		// 2.设置发件人
		message.setFrom(new InternetAddress(authenticator.getUsername()));
		// 3.设置收件人
		message.setRecipient(RecipientType.TO, new InternetAddress(recipient));
		// 4.设置邮件主题
		message.setSubject(subject);
		// 5.设置邮件内容
		message.setContent(content.toString(), "text/html;charset=utf-8");
		// 6.发送
		Transport.send(message);
	}

	/**
	 * 群发邮件
	 * 
	 * 创建时间：2018年09月03日
	 * 
	 * @author Qingtian Lei
	 * @param recipients
	 *            多个收件人（邮箱地址集合）
	 * @param subject
	 *            邮件主题
	 * @param content
	 *            邮件内容
	 */
	public MailMsg send(List<String> recipients, List<String> ccRecipients,
			String subject, Object content) {
		MailMsg mailMsg = new MailMsg();
		// 1.创建mime类型邮件
		final Message message = new MimeMessage(session);
		// 自定义发件人昵称
		String nick = "";
		try {
			nick = javax.mail.internet.MimeUtility.encodeText("宇视SDMS");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			mailMsg.setSendFlag(3);
			mailMsg.setSendMag("发件人昵称编码不正确");
			return mailMsg;
		}
		// 2.设置发件人
		try {
			message.setFrom(new InternetAddress(authenticator.getUsername(),
					nick));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			mailMsg.setSendFlag(3);
			mailMsg.setSendMag("发件人地址编码不正确");
			return mailMsg;
		} catch (MessagingException e) {
			e.printStackTrace();
			mailMsg.setSendFlag(3);
			mailMsg.setSendMag("发件人地址设置失败");
			return mailMsg;
		}
		// 3.设置收件人
		final int num = recipients.size();
		InternetAddress[] addresses = new InternetAddress[num];
		for (int i = 0; i < num; i++) {
			try {
				addresses[i] = new InternetAddress(recipients.get(i));
			} catch (Exception e) {
				e.printStackTrace();
				mailMsg.setSendFlag(3);
				mailMsg.setSendMag("收件人地址设置失败");
				return mailMsg;
			}
		}
		// 4.设置抄送人
		final int ccNum = ccRecipients.size();
		if (ccNum > 0) {
			InternetAddress[] ccAddresses = new InternetAddress[num];
			for (int i = 0; i < ccNum; i++) {
				try {
					ccAddresses[i] = new InternetAddress(ccRecipients.get(i));
				} catch (Exception e) {
					e.printStackTrace();
					mailMsg.setSendFlag(3);
					mailMsg.setSendMag("抄送人地址设置失败");
					return mailMsg;
				}
			}
			try {
				message.setRecipients(RecipientType.CC, ccAddresses);
			} catch (MessagingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				mailMsg.setSendFlag(4);
				mailMsg.setSendMag("邮件发送失败");
				return mailMsg;
			}
		}
		try {
			message.setRecipients(RecipientType.TO, addresses);
			// 5.设置邮件主题
			message.setSubject(subject);
			// 6.设置邮件内容
			message.setContent(content.toString(), "text/html;charset=utf-8");
			// 7.发送
			Transport.send(message);
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			mailMsg.setSendFlag(4);
			mailMsg.setSendMag("邮件发送失败");
			return mailMsg;
		}
		mailMsg.setSendFlag(2);
		mailMsg.setSendMag("邮件发送成功");
		return mailMsg;
	}

	public static void main(String[] args) {
		SimpleMailSenderDB simpleMailSender = new SimpleMailSenderDB(
				"10.220.3.110", "25", "true", "sdms@uniview.com", "tsnXJzNw");
		simpleMailSender.init();
		List<String> recipients = new ArrayList<String>();
		recipients.add("fangxinglong@uniview.com");
		List<String> recipientsCC = new ArrayList<String>();
		String subject = "派工系统邮催提醒：您有不满意工单需要处理，请及时跟进！";
		StringBuilder content = new StringBuilder(
				"<html><head></head><body><h2>title</h2>");
		content.append("<table border=\"5\" style=\"border:solid 1px #000000;font-size:28px;border-collapse:collapse;\">");
		content.append("<tr style=\"color:#000000\"><th>column1</th><th>column2</th><th>column3</th></tr>");
		List<ServiceOrders> list = new ArrayList<ServiceOrders>();
		ServiceOrders serviceOrder = new ServiceOrders();
		serviceOrder.setContactName("11");
		list.add(serviceOrder);
		serviceOrder.setContactName("22");
		list.add(serviceOrder);
		serviceOrder.setContactName("33");
		list.add(serviceOrder);
		for (ServiceOrders data : list) {
			content.append("<tr>");
			content.append("<td>" + data.getContactName() + "</td>"); // 第一列
			content.append("<td>" + data.getContactName() + "</td>"); // 第二列
			content.append("<td>" + data.getContactName() + "</td>"); // 第三列
			content.append("</tr>");
		}
		content.append("</table>");
		content.append("<h3>description</h3>");
		content.append("</body></html>");
		MailMsg mailMsg = simpleMailSender.send(recipients, recipientsCC,
				subject, content);
		System.out.println(mailMsg.getSendMag());
		System.out.println(mailMsg.getSendFlag());
	}
}
